﻿using Azure.Core;
using HttpServer.Models;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
using static HttpServer.Models.UserProfileData;
namespace HttpServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("Regist")]
        public IActionResult UserRegist(UserData data)
        {
            Console.WriteLine("注册账号:" + data.accountNumber);
            if (data.accountNumber.Length < 4)
            {
                Console.WriteLine("Account Number length cannot be less than 4.");
                return StatusCode(200, new RequestData(1001, "Account Number length cannot be less than 4."));
            }
            if (data.password.Length < 6)
            {
                Console.WriteLine("Password length cannot be less than 6.");
                return StatusCode(200, new RequestData(1002, "Password length cannot be less than 6."));
            }
            //检查是否已经有用户名
            var catchExistsRequestData = SqlLinkManager.GetData("user", "accountNumber", data.accountNumber);
            if (catchExistsRequestData != null)
            {
                Console.WriteLine("AccountNumber already registered.");
                return StatusCode(200, new RequestData(3001, "AccountNumber already registered."));
            }
            //数据库添加用户名密码
            int dataIndex = SqlLinkManager.InsertData("user",
                new KeyStringValuePack("accountNumber", data.accountNumber),
                new KeyStringValuePack("password", data.password),
                new KeyStringValuePack("registTimeStamp", DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
                );

            SqlLinkManager.InsertData("userProfile", new KeyIntValuePack("userId", dataIndex),
                new KeyStringValuePack("accountNumber", data.accountNumber),
                new KeyStringValuePack("nickname", data.accountNumber),
                new KeyStringValuePack("registTimeStamp", DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
                );
            //Console.WriteLine(dataIndex);
            //获取用户信息并返回
            var requestObject = SqlLinkManager.GetData<UserProfileData>("userProfile", "userId", dataIndex.ToString());
            if (requestObject != null)
            {
                Console.WriteLine("注册成功");
                return StatusCode(200, new RequestData(200, "Regist Successful!", requestObject));
            }
            Console.WriteLine("Error.");
            return StatusCode(400, "Error");
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="accountNumber">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpGet("Login")]
        public IActionResult UserLogin([FromQuery] string accountNumber, [FromQuery] string password)
        {
            //string[] dataStages = data.Split('&');
            if (string.IsNullOrEmpty(accountNumber) || string.IsNullOrEmpty(password))
            {
                Console.WriteLine("Account Number or Password Can not be null.");
                return StatusCode(200, new RequestData(1003, "Account Number or Password Can not be null"));
            }
            //string accountNumber = dataStages[0];
            //string password = dataStages[1];
            using (MySqlConnection connection = new MySqlConnection(SqlLinkManager.sqlConnectionCommand))
            {
                try
                {
                    connection.Open();
                    using (MySqlCommand command = new MySqlCommand(SqlLinkManager.GetSearchCommand("user", "accountNumber", $"\"{accountNumber}\""), connection))
                    {
                        UserData userData = new UserData();
                        MySqlDataReader dr = command.ExecuteReader();

                        while (dr.Read())
                        {
                            userData.userId = dr["userId"] == DBNull.Value ? -1 : (int)dr["userid"];
                            userData.accountNumber = dr["accountNumber"] == DBNull.Value ? "" : (string)dr["accountNumber"];
                            userData.password = dr["password"] == DBNull.Value ? "" : (string)dr["password"];
                            if (userData.userId == -1)
                            {
                                Console.WriteLine("Cant Find Account!");
                                return StatusCode(200, new RequestData(3002, "Cant Find Account!"));
                            }
                            if (userData.password == password)
                            {
                                //获取用户信息并返回
                                var requestObject = SqlLinkManager.GetData<UserProfileData>("userProfile", "userId", userData.userId.ToString());
                                if (requestObject != null)
                                {

                                    return StatusCode(200, new RequestData(200, "Login Successful!", requestObject));
                                }
                                else
                                {
                                    SqlLinkManager.InsertData("userProfile", new KeyIntValuePack("userId", userData.userId),
                                        new KeyStringValuePack("accountNumber", userData.accountNumber),
                                        new KeyStringValuePack("nickname", userData.accountNumber),
                                        new KeyStringValuePack("registTimeStamp", DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
                                        );
                                    //Console.WriteLine(dataIndex);
                                    //获取用户信息并返回
                                    requestObject = SqlLinkManager.GetData<UserProfileData>("userProfile", "userId", userData.userId.ToString());
                                    if (requestObject != null)
                                    {
                                        return StatusCode(200, new RequestData(200, "Login Successful!", requestObject));
                                    }
                                }
                            }
                        }
                        Console.WriteLine("Account Number or Password Erorr");
                        return StatusCode(200, new RequestData(2001, "Account Number or Password Erorr"));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("连接失败:" + e);
                }
                finally
                {
                    connection.Close();
                }

            }
            Console.WriteLine("Error");
            return StatusCode(400, "Error");
        }

        ///// <summary>
        ///// 查找用户
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet("GetUser/{id}")]
        //public IActionResult GetUser(int id)
        //{
        //    using (MySqlConnection connection = new MySqlConnection(SqlLinkManager.sqlConnectionCommand))
        //    {
        //        try
        //        {
        //            connection.Open();
        //            using (MySqlCommand command = new MySqlCommand(SqlLinkManager.GetSearchCommand("user", "userId", id), connection))
        //            {
        //                UserData userData = new UserData();
        //                MySqlDataReader dr = command.ExecuteReader();
        //                while (dr.Read())
        //                {
        //                    userData.userId = dr["userId"] == DBNull.Value ? -1 : (int)dr["userid"];
        //                    userData.accountNumber = dr["accountNumber"] == DBNull.Value ? "" : (string)dr["accountNumber"];
        //                    userData.password = dr["password"] == DBNull.Value ? "" : (string)dr["password"];
        //                }
        //                return StatusCode(200, JsonConvert.SerializeObject(userData));
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            Console.WriteLine("连接失败:" + e);
        //        }
        //        finally
        //        {
        //            connection.Close();
        //        }

        //    }
        //    return StatusCode(400, "Database Error!");
        //}

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete/{id}")]
        public IActionResult DeleteUser([FromQuery] string accountNumber, [FromQuery] string password)
        {
            using (MySqlConnection connection = new MySqlConnection(SqlLinkManager.sqlConnectionCommand))
            {
                try
                {
                    connection.Open();
                    int userId = -1;
                    string checkQuery = $"SELECT * FROM user WHERE accountNumber = \"{accountNumber}\"";
                    using (var command = new MySqlCommand(checkQuery, connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                if (reader["accountNumber"] != DBNull.Value)
                                {
                                    if ((string)reader["password"] == password)
                                    {

                                    }
                                    else
                                    {
                                        return StatusCode(200, new RequestData(2001, "Password Erorr!"));
                                    }
                                }
                            }
                        }
                    }
                    if (userId == -1)
                    {
                        return StatusCode(400, "Account Not Found.");
                    }
                    string query = $"DELETE FROM users WHERE userId = {userId}";
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        int rowsAffected = command.ExecuteNonQuery();
                        if (rowsAffected > 0)
                        {
                            Console.WriteLine($"删除用户:{accountNumber}");
                            return StatusCode(200);

                        }
                        else
                        {
                            Console.WriteLine($"未找到该用户！:{accountNumber}");
                            return StatusCode(200, new RequestData(3002, "Account Not Found!"));

                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("连接失败:" + e);
                }
                finally
                {
                    connection.Close();
                }

            }
            return StatusCode(400, "Error");
        }
    }
}
